﻿using Moven.Data;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace Moven.ViewModels
{
    public class ArticleWithBookmark: BaseViewModel
    {
        public new string Title => Article.Title;
        public int Index => Article.Index;
        public string Url => Article.Url;
        public string[] Tags => Article.Tags;
		public string Date => Article.Date;

		bool _isNew;
		public bool IsNew
		{
			get { return _isNew; }
			set { SetProperty(ref _isNew, value); }
		}

        public string JoinedTags => "分类: " + Article.JoinedTags;

		public ViewCell ViewCell { get; set; }

		public View View => ViewCell?.View;

        bool _isBookmarked;
        public bool IsBookmarked
        {
            get { return _isBookmarked; }
			set 
			{ 
				SetProperty(ref _isBookmarked, value); 
			}
        }

		bool _isSelected;
		public bool IsSelected
		{
			get { return _isSelected; }
			set { SetProperty(ref _isSelected, value); }
		}

        Article Article { get; }
        public ArticleWithBookmark(Article article)
        {
            Article = article;
        }

		Command _toggleCommand;

		public Command ToggleCommand => _toggleCommand ?? 
			(_toggleCommand = new Command(() => IsSelected = !IsSelected));

        public static ArticleWithBookmark FromArticle(Article article) => new ArticleWithBookmark(article);
        public static Article ToArticle(ArticleWithBookmark article) => article.Article;

        public static async Task UpdateBookmarksAsync(IEnumerable<ArticleWithBookmark> articles)
        {
            var bookmarks = await Statics.ArticlesStore.GetBookmarksAsync();
			articles.ForEach(article => article.IsBookmarked = bookmarks.Contains(article.Index));
        }
    }
}
